import React from 'react';
import {Table, Card, Divider} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {partClaimType, partClaimDecisionStatus, partPaymentMethod, currency} from '../Enum';
import {TABLE, PAGINATION_OPTIONS, FIXED_COLUMN_WIDTH, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, DATE_FORMAT} from '../constants';

export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };

    render() {
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, total} = this.props;
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.code',
                defaultMessage: '编号'
            }),
            dataIndex: 'code',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
            render: (text, record) => <Link key="detail" to={routes.detail.format(record.id)}>{text}</Link>
        }, {
            title: formatMessage({
                id: 'tablePanel.column.brandName',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brandName',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'brandName' && this.props.sortedOrder,
            render: (text, r) => `(${r.brandCode})${r.brandName}`
        }, {
            title: formatMessage({
                id: 'tablePanel.column.invoiceCode',
                defaultMessage: '发票号'
            }),
            dataIndex: 'invoiceCode',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.invoicedDate',
                defaultMessage: '开票日期'
            }),
            dataIndex: 'invoicedDate',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'status' && this.props.sortedOrder,
            render: text => conventEnumValueToString(partClaimDecisionStatus, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.claimType',
                defaultMessage: '索赔类型'
            }),
            dataIndex: 'claimType',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'claimType' && this.props.sortedOrder,
            render: text => conventEnumValueToString(partClaimType, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.paymentMethod',
                defaultMessage: '赔付方式'
            }),
            dataIndex: 'paymentMethod',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'paymentMethod' && this.props.sortedOrder,
            render: text => conventEnumValueToString(partPaymentMethod, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'currency' && this.props.sortedOrder,
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.claimFee',
                defaultMessage: '索赔总金额'
            }),
            dataIndex: 'claimFee',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'claimFee' && this.props.sortedOrder,
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.claimAmount',
                defaultMessage: '索赔总数量'
            }),
            dataIndex: 'claimAmount',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'claimAmount' && this.props.sortedOrder,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.createTime',
                defaultMessage: '提报日期'
            }),
            dataIndex: 'createTime',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'createTime' && this.props.sortedOrder,
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.approverTime',
                defaultMessage: '审核日期'
            }),
            dataIndex: 'approverTime',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'approverTime' && this.props.sortedOrder,
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.confirmTime',
                defaultMessage: '确认日期'
            }),
            dataIndex: 'confirmTime',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'confirmTime' && this.props.sortedOrder,
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.operate',
                defaultMessage: '操作'
            }),
            dataIndex: 'operate',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (text, record) => {
                const approveOpt = hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(record.options, PERMISSION.approve) &&
                    <Link key="approve" to={routes.approve.format(record.id)}>{
                        formatMessage({
                            id: 'tablePanel.operation.approve',
                            defaultMessage: '审核'
                        })
                    }</Link>;
                const confirmOpt = hasPermissions(this.props.permissions, PERMISSION.confirm) && hasPermissions(record.options, PERMISSION.confirm) &&
                    <Link key="confirm" to={routes.confirm.format(record.id)}>{
                        formatMessage({
                            id: 'tablePanel.operation.confirm',
                            defaultMessage: '确认'
                        })
                    }</Link>;
                return <span>{approveOpt}{approveOpt && confirmOpt && <Divider key="divider" type="vertical"/>}{confirmOpt}</span>;
            }
        }];
        if(!this.props.isDealerUser)
            columns.splice(2, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.dealerCode',
                        defaultMessage: '总代编号'
                    }),
                    sorter: true,
                    sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder,
                    dataIndex: 'dealerCode',
                },
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.dealerName',
                        defaultMessage: '总代名称'
                    }),
                    dataIndex: 'dealerName'
                },
            ]);
        return (
            <Card>
                <Table
                    className={'white-space-nowrap'}
                    columns={columns}
                    dataSource={this.props.data}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    pagination={pagination}
                    rowKey="id"
                    locale={locale}
                    {...TABLE}/>
            </Card>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';
import {injectIntl} from './intl';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
    isDealerUser: state.getIn(['page', 'domainData', 'init', 'isDealerUser']),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));


